<template>
  <div class="node-mysql">
    <el-form :model="Database" class="node-mysqlq" size="small" label-width="90px" label-position="left">
      <div class="db-sql-param">
        <el-form-item label="选择数据库">
          <el-select
              filterable
              v-model="Database.DatabaseId"
              placeholder="请选择数据库"
              size="small"
          >
            <el-option
                v-for="item in OptionDatabase"
                :key="item.Id"
                :label="item.DeviceName"
                :value="item.Id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="高级操作">
          <el-button-group class="ml-4">
            <el-button @click="EditSqlBtn" type="primary" icon="Plus">配置</el-button>
            <!--            <el-button @click="EditSqlBtn" type="primary" icon="Edit">修改</el-button>-->
            <!--            <el-button @click="EditSqlBtn" type="primary" icon="Delete">删除</el-button>-->
            <!--            <el-button @click="EditSqlBtn" type="primary" icon="Search">查询</el-button>-->
          </el-button-group>
        </el-form-item>
        <div>
          <label>
            输入变量
          </label>
          <el-icon @click.prevent="AddSqlInputParam()" circle
                   class="el-icon-circle-plus-outline m-top-10 m-bottom-10 cursor-pointer">
            <CirclePlus/>
          </el-icon>
        </div>
        <div class="db-sql-param-list">
          <div
              class="db-sql-param-item"
              v-for="(WhereParam,wp_index) in Database.WhereParams"
              :key="wp_index"
          >
            <el-tag class="margin-right-10">{ {{ wp_index }} }</el-tag>
            <data-source-input
                :datasource-item="WhereParam"
                :node-id="WhereParam.DataSourceId"
                :param-name="WhereParam.ParamName"
                null-message="请选择数据来源（不能为空）"
                @change="onChange($event,wp_index)"
                style="max-width: 300px;width: 225px;margin-left: 6px"
            />
            <el-button
                icon="Delete"
                style="color: red"
                @click.prevent="DeleteSqlInputParam(wp_index)"
                type="text"
                size="small"
                circle
            ></el-button>
          </div>
        </div>
      </div>
      <el-form-item label="SQL编辑">
        <el-input
            v-model="Database.Sql"
            type="textarea"
            :rows="10"
            placeholder="请编辑SQL"
            style="width: 90%"
        ></el-input>
      </el-form-item>
      <el-form-item label="描述">
        <el-input
            v-model="Database.Desc"
            type="textarea"
            :rows="3"
            placeholder="请输入描述（可选）"
            style="width: 90%"
        ></el-input>
      </el-form-item>
      <el-form-item label="SQL例子">
        <div class="sql-item-ex">
          <el-tag type="primary">新增1：INSERT INTO students (name, age, gender) VALUES ('张三', 20, '男');</el-tag>
        </div>
        <div class="sql-item-ex">
          <el-tag type="primary">新增2：INSERT INTO students (name, age, gender)
            VALUES
            ('李四', 21, '女'),
            ('王五', 19, '男');
          </el-tag>
        </div>
        <div class="sql-item-ex">
          <el-tag type="success">修改：UPDATE students SET age = 21,gender = '女' WHERE name = '张三';</el-tag>
        </div>
        <div class="sql-item-ex">
          <el-tag type="danger">删除：DELETE FROM students WHERE age = 21;</el-tag>
        </div>
        <div class="sql-item-ex">
          <el-tag type="danger">删除所有：DELETE FROM students;</el-tag>
        </div>
        <div class="sql-item-ex">
          <el-tag type="warning">查询：SELECT * FROM students where name = '张三';</el-tag>
        </div>
        <div class="sql-item-ex">
          <el-tag type="warning">查询一条：SELECT top 1 * FROM students where name = '张三';</el-tag>
        </div>
        <div class="sql-item-ex">
          <el-tag type="warning">分页：SELECT * FROM students where name = '张三' limit 0,10;</el-tag>
        </div>
        <div class="sql-item-ex">
          <el-tag type="warning">
            CURRENT_TIMESTAMP = YYYY-MM-DD HH:MM:SS | CURRENT_DATE = YYYY-MM-DD | CURRENT_TIME = HH:MM:SS
<!--            &#45;&#45; 其中，new_value是你希望设置的新的自增起始值。例如，要将自增起始值设置为 100，可以执行ALTER TABLE your_table_name AUTO_INCREMENT = 100;-->
          </el-tag>
        </div>
      </el-form-item>
    </el-form>
    <el-dialog
        v-model="ShowSeniorOperationDialog"
        title="SQL生成"
        width="600"
        draggable
        overflow
    >
      <senior-operation @close="onClose"/>
    </el-dialog>
  </div>
</template>
<script>

import FlowNodeDataApi from '@/api/flow/FlowNodeDataApi'
import { AppParams } from '@/utils/appParams'
import Utils from '../../../../utils/Common'
import { createNamespacedHelpers } from 'vuex'
import { DataManage } from '@/api/DataManageApi'
import NodeConfigMixin from '../../../../libs/NodeConfigMixin'
import DataSourceInput from '../../components/NodeInputSourceDataComponent.vue'
import SeniorOperation from './SeniorOperation.vue'

const { mapState } = createNamespacedHelpers('flow/chat')
const { mapState: mapNodeParamsState } = createNamespacedHelpers('NodeParams')

export default {
  name: 'DBMySql',
  mixins: [NodeConfigMixin],
  components: { SeniorOperation, DataSourceInput },
  data () {
    return {
      ShowSeniorOperationDialog: false,
      OptionDatabase: [],
      OptionTables: [],
      comparisonOperators: AppParams.COMMON.DATABASE_OPERATIONS,
      Database: {
        DatabaseId: 0,
        WhereParams: [],
        Sql: null,
        Operation: null,
        TableName: null,
        ParamName: null,
        TargetId: null,
        address: null,
        NodeId: true,
        IsAddressHub: true,
        Desc: null
      },
      DriveDBReadDialogVisible: false,
      TableResult: {}
    }
  },
  computed: {
    ...mapState({
      currentClickNode: state => state.currentClickNode
    }),
    ...mapNodeParamsState({
      optionDrivers: state => state.driver
    })
  },
  methods: {
    onClose (Result) {
      console.log(Result)
      this.Database.Sql = Result.SqlResult
      this.TableResult = Result
      this.ShowSeniorOperationDialog = false
    },
    /**
     *
     * @param operation
     * @constructor
     */
    EditSqlBtn (operation) {
      this.ShowSeniorOperationDialog = true
    },
    onChange (item, itemIndex) {
      if (!Utils.IsEmpty(item)) {
        this.Database.WhereParams[itemIndex].ParamName = item.ParamName
        this.Database.WhereParams[itemIndex].DataSource = item.DataSource
        this.Database.WhereParams[itemIndex].DataSourceId = item.nodeId
      }
    },
    DeleteSqlInputParam (index) {
      this.Database.WhereParams.splice(index, 1)
    },
    AddSqlInputParam () {
      let WhereParams = this.Database.WhereParams || []
      if (Utils.IsEmpty(WhereParams)) {
        WhereParams = [{
          TargetParamName: WhereParams.length,
          ParamName: null,
          ValueType: 'int'
        }]
      } else {
        WhereParams.push({
          TargetParamName: WhereParams.length,
          ParamName: null,
          ValueType: 'int'
        })
      }
      this.Database.WhereParams = WhereParams
    },
    ShowNodeData () {
      this.OptionDatabase = this.optionDrivers.filter(o => ['MYSQL', 'SQLITE'].includes(o.DeviceType))
      this.OptionDatabase.push({ Id: 0, DeviceName: '内置数据库' })
      this.DriveDBReadDialogVisible = true
      this.SetFormValue(this.currentClickNodeMixin)
      this.InitNodeData(this.Database.DataSourceId)
    },
    /**
     * 设置回显的表单数据
     * @param _node
     * @constructor
     */
    SetFormValue (_node) {
      if (!Utils.IsEmpty(_node?.nodeInputParam?.Database)) {
        const nip = _node.nodeInputParam
        this.Database.Sql = nip.Database.Sql
        this.Database.Desc = nip.Desc
        this.Database.DatabaseId = nip.Database.DatabaseId
        this.Database.WhereParams = nip.Database.WhereParams
      }
    },
    /**
     * 选中的值
     * @param item
     */
    onDBChange (item) {
      if (!Utils.IsEmpty(item)) {
        DataManage.FindSystemDatabaseTableNames().then((res) => {
          this.OptionTables = res
        })
      }
    },
    /**
     * 初始化节点数据
     * @constructor
     */
    InitNodeData (DataSourceId) {
      this.onDBChange(DataSourceId)
    },
    _SaveNode (NodeName) {
      const _DB = this.Database
      const params = {
        Database: _DB,
        Desc: _DB.Desc
      }
      new FlowNodeDataApi().Install(this.currentClickNodeMixin.id, params, NodeName)
    }
  },
  mounted () {
    this.ShowNodeData()
  }
}
</script>

<style>
.node-mysqlq {
  overflow-x: auto;
  height: calc(100vh - 220px);
}
</style>
<style lang="less">

.node-mysql {

  .sql-item-ex {
    width: 100%;
    user-select: text;
  }

  .db-sql-param {
    padding-right: 10px;
    padding-bottom: 10px;

    .db-sql-param-list {
      overflow-y: auto;
    }

    .db-sql-param-item {
      display: flex;
      padding-top: 10px;
      align-items: center;
    }
  }
}
</style>
